<template>
  <div class="summary-container">
    <h2 class="summary-title">数据中心
      <span class="view-more" @click="toggleView">
        {{ isShowAll ? '收起' : '查看更多' }} <i class="arrow-icon" :class="{ 'rotated': isShowAll }">›</i>
      </span>
    </h2>

    <div class="cards-container">
      <div v-for="(item, index) in visibleModules" :key="index" class="stat-card" :class="item.class">
        <div class="card-title">{{ item.title }}</div>
        <div class="card-value">{{ formatNumber(countData[item.key] || 0) }}</div>
      </div>
    </div>

    <!-- 折线图容器 -->
<!--    <div class="chart-container">-->
<!--      <div class="chart-header">-->
<!--        <div class="chart-title">成果趋势图</div>-->
<!--        <div class="chart-controls">-->
<!--          <div class="time-range">-->
<!--            <span-->
<!--                v-for="(range, index) in timeRanges"-->
<!--                :key="index"-->
<!--                :class="{ 'active': selectedTimeRange === range.value }"-->
<!--                @click="changeTimeRange(range.value)"-->
<!--            >-->
<!--              {{ range.label }}-->
<!--            </span>-->
<!--          </div>-->
<!--          <div class="legend-toggle">-->
<!--            <el-switch-->
<!--                v-model="showAllSeries"-->
<!--                active-text="显示全部"-->
<!--                inactive-text="精简显示"-->
<!--                @change="toggleSeriesDisplay"-->
<!--            />-->
<!--          </div>-->
<!--        </div>-->
<!--      </div>-->
<!--      <div ref="chartRef" class="chart"></div>-->
<!--    </div>-->
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch, onBeforeUnmount } from 'vue';
import { getSummaryCount, getSummaryCountByTime } from "@/api/home";
import * as echarts from 'echarts';
import { ElSwitch, ElMessage } from 'element-plus';

// 初始化模块数据
const countData = ref({
  personalAwardCount: 0,
  studentAwardCount: 0,
  certificateCount: 0,
  copyrightCount: 0,
  horizontalProjectsCount: 0,
  longitudinalProjectsCount: 0,
  continuingEducationCount: 0,
  otherCount: 0,
  papersCount: 0,
  patentsCount: 0,
  publicationCount: 0,
  reportCount: 0
});

// 控制显示所有模块还是部分模块
const isShowAll = ref(false);

// 模块列表，包含每个模块的显示标题、样式、以及对应的数据字段
const modules = [
  { title: "论文数", class: "navy-blue", key: "papersCount" },
  { title: "著作数", class: "orange", key: "publicationCount" },
  { title: "专利数", class: "light-blue", key: "patentsCount" },
  { title: "纵向课题", class: "blue", key: "longitudinalProjectsCount" },
  { title: "证书", class: "green", key: "certificateCount" },
  { title: "著作权", class: "bright-green", key: "copyrightCount" },
  { title: "报告", class: "pink", key: "reportCount" },
  { title: "个人奖励", class: "red", key: "personalAwardCount" },
  { title: "学生奖励", class: "purple", key: "studentAwardCount" },
  { title: "横向课题", class: "teal", key: "horizontalProjectsCount" },
  { title: "继续教育", class: "brown", key: "continuingEducationCount" },
  { title: "其他", class: "gray", key: "otherCount" }
];

// 获取前 8 个或所有模块
const visibleModules = computed(() => {
  return isShowAll.value ? modules : modules.slice(0, 8);
});

// 格式化数字，添加千位分隔符
const formatNumber = (num) => {
  return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
};

// 获取数据
const fetchData = async () => {
  try {
    const response = await getSummaryCount();
    if (response.code === 200 && response.data) {
      countData.value = response.data;
    } else {
      console.error('获取数据失败:', response.msg || '未知错误');
      ElMessage.error('获取统计数据失败');
    }
  } catch (error) {
    console.error('获取数据异常:', error);
    ElMessage.error('获取统计数据出现异常');
  }
};

const toggleView = () => {
  isShowAll.value = !isShowAll.value;
};

// 折线图相关
const chartRef = ref(null);
let chart = null;
const chartData = ref({
  years: [],
  dataMap: {}
});
const loading = ref(false);
const showAllSeries = ref(true);
const selectedTimeRange = ref('all');

// 时间范围选项
const timeRanges = [
  { label: '全部', value: 'all' },
  { label: '近5年', value: '5years' },
  { label: '近10年', value: '10years' }
];

// 系列颜色映射
const seriesColors = {
  '专利': '#5470c6',
  '个人获奖': '#91cc75',
  '其他': '#fac858',
  '档案资料': '#ee6666',
  '继续教育材料': '#73c0de',
  '纵向课题': '#3ba272',
  '横向课题': '#fc8452',
  '软件著作权': '#9a60b4',
  '论文': '#ea7ccc',
  '著作': '#5470c6',
  '新闻报道': '#91cc75',
  '学生获奖': '#c23531'
};

// 主要系列（精简显示时只显示这些）
const mainSeries = ['论文', '专利', '软件著作权', '著作', '纵向课题'];

// 获取所有用户的模块统计数据
const fetchMetricsData = async () => {
  try {
    loading.value = true;
    const response = await getSummaryCountByTime();
    console.log('获取趋势数据成功:', response);

    if (response && response.code === 200 && response.data) {
      const responseData = response.data;

      // 确保years是数组并且有值
      if (Array.isArray(responseData.years) && responseData.years.length > 0) {
        chartData.value.years = [...responseData.years];
        console.log('成功获取years数组:', chartData.value.years);
      } else {
        console.warn('未找到years数组或格式不正确');
        chartData.value.years = []; // 设置为空数组
      }

      // 处理数据系列
      const dataMap = {};

      if (responseData.data && typeof responseData.data === 'object') {
        Object.keys(responseData.data).forEach(key => {
          if (Array.isArray(responseData.data[key])) {
            dataMap[key] = [...responseData.data[key]];
          }
        });
      } else {
        Object.keys(responseData).forEach(key => {
          if (key !== 'years' && Array.isArray(responseData[key])) {
            dataMap[key] = [...responseData[key]];
          }
        });
      }

      chartData.value.dataMap = dataMap;
      console.log('处理后的chartData:', chartData.value);
    } else {
      console.error('获取趋势数据失败:', response?.msg || '未知错误');
      ElMessage.error('获取趋势数据失败');
    }
  } catch (error) {
    console.error('获取趋势数据异常:', error);
    ElMessage.error('获取趋势数据出现异常');
  } finally {
    loading.value = false;
    renderChart();
  }
};

// 根据选择的时间范围过滤数据
const getFilteredData = () => {
  if (!chartData.value || !chartData.value.years || !chartData.value.dataMap) {
    console.warn('原始数据无效');
    return {
      years: [],
      dataMap: {}
    };
  }

  const { years, dataMap } = chartData.value;

  if (selectedTimeRange.value === 'all' || !years.length) {
    return chartData.value;
  }

  const currentYear = new Date().getFullYear();
  const yearsToShow = selectedTimeRange.value === '5years' ? 5 : 10;
  const startYear = currentYear - yearsToShow;

  // 找到起始年份在数据中的索引
  const startIndex = years.findIndex(year => parseInt(year) >= startYear);

  if (startIndex === -1) {
    console.warn('未找到符合条件的年份');
    return chartData.value;
  }

  // 过滤数据
  const filteredYears = years.slice(startIndex);
  const filteredDataMap = {};

  if (dataMap && typeof dataMap === 'object') {
    Object.keys(dataMap).forEach(key => {
      if (Array.isArray(dataMap[key])) {
        filteredDataMap[key] = dataMap[key].slice(startIndex);
      }
    });
  }

  return {
    years: filteredYears,
    dataMap: filteredDataMap
  };
};

// 切换时间范围
const changeTimeRange = (range) => {
  selectedTimeRange.value = range;
  renderChart();
};

// 切换系列显示
const toggleSeriesDisplay = () => {
  renderChart();
};

// 渲染图表
const renderChart = () => {
  if (!chart) {
    console.warn('图表实例未初始化');
    return;
  }

  const filteredData = getFilteredData();
  if (!filteredData || !filteredData.years || filteredData.years.length === 0) {
    console.error('过滤后的数据无效或年份数据为空');
    return;
  }

  const { years, dataMap } = filteredData;

  // 准备系列数据
  let allSeries = [];

  if (dataMap && typeof dataMap === 'object' && Object.keys(dataMap).length > 0) {
    allSeries = Object.keys(dataMap).map(key => ({
      name: key,
      data: Array.isArray(dataMap[key]) ? dataMap[key] : []
    }));
  } else {
    console.warn('数据为空或格式不正确，无法渲染图表');
    return;
  }

  // 根据显示设置过滤系列
  const displaySeries = showAllSeries.value
      ? allSeries
      : allSeries.filter(series => mainSeries.includes(series.name));

  // 构建图表配置
  const option = {
    title: {
      text: '成果趋势图',
      left: 'center',
      top: 0,
      textStyle: {
        fontSize: 16,
        fontWeight: 'normal'
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: function(params) {
        if (!params || params.length === 0) return '';

        let result = `<div style="font-weight:bold;margin-bottom:5px;">${params[0].axisValue}年</div>`;

        // 对数据进行排序，数值大的在前面
        params.sort((a, b) => b.value - a.value);

        params.forEach(param => {
          if (param && param.seriesName) {  // 确保param对象有效
            const color = param.color || '#5470c6';
            const name = param.seriesName;
            const value = param.value || 0;
            result += `<div style="display:flex;justify-content:space-between;align-items:center;margin:3px 0;">
                      <span style="display:inline-block;margin-right:5px;width:10px;height:10px;border-radius:50%;background-color:${color};"></span>
                      <span style="flex:1;text-align:left;">${name}:</span>
                      <span style="font-weight:bold;">${value}</span>
                    </div>`;
          }
        });

        return result;
      }
    },
    legend: {
      data: displaySeries.map(item => item.name),
      top: 30,
      type: 'scroll',
      pageIconSize: 12,
      pageTextStyle: {
        color: '#888'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: 80,
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: years,
      axisLabel: {
        formatter: '{value}年'
      }
    },
    yAxis: {
      type: 'value',
      splitLine: {
        lineStyle: {
          type: 'dashed'
        }
      }
    },
    series: displaySeries.map(item => ({
      name: item.name,
      type: 'line',
      data: item.data,
      smooth: true,
      symbol: 'emptyCircle',
      symbolSize: 6,
      lineStyle: {
        width: 2,
        color: seriesColors[item.name] || '#5470c6'
      },
      itemStyle: {
        color: seriesColors[item.name] || '#5470c6'
      },
      emphasis: {
        focus: 'series',
        itemStyle: {
          borderWidth: 2
        }
      },
      areaStyle: {
        opacity: 0.1,
        color: seriesColors[item.name] || '#5470c6'
      }
    }))
  };

  // 设置加载状态
  if (loading.value) {
    chart.showLoading({
      text: '加载中...',
      maskColor: 'rgba(255, 255, 255, 0.8)',
      fontSize: 14
    });
  } else {
    chart.hideLoading();
  }

  try {
    // 应用配置
    chart.setOption(option, true);
  } catch (error) {
    console.error('设置图表选项时出错:', error);
  }
};

// 监听窗口大小变化
const handleResize = () => {
  if (chart) {
    chart.resize();
  }
};

// 组件挂载时执行
onMounted(() => {
  // 获取统计数据
  fetchData();

  // // 初始化ECharts实例
  // if (chartRef.value) {
  //   try {
  //     chart = echarts.init(chartRef.value);
  //
  //     // 显示加载中状态
  //     chart.showLoading({
  //       text: '加载中...',
  //       maskColor: 'rgba(255, 255, 255, 0.8)',
  //       fontSize: 14
  //     });
  //
  //     // 获取趋势数据并渲染图表
  //     fetchMetricsData();
  //   } catch (error) {
  //     console.error('初始化图表时出错:', error);
  //     ElMessage.error('初始化图表时出错');
  //   }
  // }

  // 监听窗口大小变化
  window.addEventListener('resize', handleResize);
});

// 监听数据变化，重新渲染图表
watch(chartData, () => {
  if (chart) {
    renderChart();
  }
}, { deep: true });

// 组件卸载前清理
onBeforeUnmount(() => {
  if (chart) {
    chart.dispose();
    chart = null;
  }
  window.removeEventListener('resize', handleResize);
});
</script>

<style scoped>
.summary-container {
  padding: 20px;
  background-color: #ffffff;
  border-radius: 8px;
  width: 100%;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.summary-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.view-more {
  font-size: 14px;
  color: #909399;
  cursor: pointer;
  display: flex;
  align-items: center;
  transition: all 0.3s;
}

.view-more:hover {
  color: #409EFF;
}

.arrow-icon {
  font-style: normal;
  margin-left: 4px;
  transition: transform 0.3s;
}

.arrow-icon.rotated {
  transform: rotate(90deg);
}

.cards-container {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  margin-bottom: 30px;
}

.stat-card {
  flex: 1;
  min-width: 120px;
  padding: 15px;
  border-radius: 6px;
  color: white;
  display: flex;
  flex-direction: column;
  justify-content: center;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transition: transform 0.3s, box-shadow 0.3s;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
}

.card-title {
  font-size: 14px;
  margin-bottom: 10px;
}

.card-value {
  font-size: 24px;
  font-weight: bold;
}

/* 卡片颜色 */
.navy-blue { background-color: #324057; }
.orange { background-color: #f5a623; }
.light-blue { background-color: #20a0ff; }
.blue { background-color: #4a6fe3; }
.green { background-color: #13ce66; }
.bright-green { background-color: #67c23a; }
.pink { background-color: #e74c8c; }
.red { background-color: #f56c6c; }
.purple { background-color: #9c27b0; }
.teal { background-color: #009688; }
.brown { background-color: #795548; }
.gray { background-color: #607d8b; }

/* 折线图样式 */
.chart-container {
  margin-top: 30px;
  width: 100%;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 10px;
}

.chart-title {
  font-size: 18px;
  font-weight: bold;
}

.chart-controls {
  display: flex;
  align-items: center;
  gap: 20px;
}

.time-range {
  display: flex;
  gap: 10px;
}

.time-range span {
  padding: 5px 10px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  color: #606266;
  background-color: #f5f7fa;
  transition: all 0.3s;
}

.time-range span:hover {
  background-color: #e6f1fc;
  color: #409EFF;
}

.time-range span.active {
  background-color: #409EFF;
  color: white;
}

.legend-toggle {
  display: flex;
  align-items: center;
}

.chart {
  width: 100%;
  height: 400px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .cards-container {
    flex-direction: column;
  }

  .stat-card {
    width: 100%;
  }

  .chart-header {
    flex-direction: column;
    align-items: flex-start;
  }

  .chart-controls {
    width: 100%;
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .chart {
    height: 300px;
  }
}
</style>
